/**
 * BilbaoUtils.cpp
 *
 * @author Bematech S.A.
 */

#include "bilbao/util/BilbaoUtils.h"

namespace bilbao
{
	namespace util
	{
		//--------------------------------------------------------------------------------
		BilbaoUtils::BilbaoUtils(void)
		{

		}
		//--------------------------------------------------------------------------------
		BilbaoUtils::~BilbaoUtils(void)
		{

		}
		//--------------------------------------------------------------------------------
		int BilbaoUtils::calcDVBase2_9Mod11(const String& num)
		{
			int dv = -1;

			if (num.length() > 0)
			{
				int k = 9;

				dv = 0;
				for (int i = num.length() - 1; i >= 0; i--)
				{
					dv += (num[i] - '0')/*atoi*/* k;
					if (k <= 2)
					{
						k = 9;
					}
					k--;
				}

				dv %= 11;
				dv = (dv == 0 || dv == 1) ? 0 : 11 - dv;

			}

			//Error
			return dv;
		}
		//--------------------------------------------------------------------------------
		int BilbaoUtils::RandomNumber(void)
		{
			return rand() % 999999;
		}
		//--------------------------------------------------------------------------------
		bool BilbaoUtils::FileExists( String strFilename )
		{
			struct stat stFileInfo;
			return !stat( strFilename.c_str(), &stFileInfo );;
		}
		//--------------------------------------------------------------------------------
		int BilbaoUtils::FileSize( String strFilename )
		{
			long begin,end;
			std::ifstream myfile (strFilename.c_str());
			begin = myfile.tellg();
			myfile.seekg (0, std::ios::end);
			end = myfile.tellg();
			myfile.close();
			return (end-begin);
		}
		//--------------------------------------------------------------------------------
		std::string BilbaoUtils::File2String( std::string file )
		{
			std::ifstream fin(file.c_str());
			char buff[1024];
			StringStream ss;

			while(fin)
			{
				fin.getline(buff, 1024);
				ss << buff;
			}

			return ss.str();
		}
		//--------------------------------------------------------------------------------
	}
}
